package com.probox.common.entity.service.system.impl;

import cn.hutool.core.util.ObjectUtil;

import com.probox.common.core.constant.CachePrefix;

import com.probox.common.core.enums.ReginType;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.system.SysArea;
import com.probox.common.entity.domain.system.SysCity;
import com.probox.common.entity.domain.system.SysProvince;
import com.probox.common.entity.domain.system.SysRegin;

import com.probox.common.entity.mapper.system.SysRegionMapper;
import com.probox.common.entity.service.system.ReginService;
import com.probox.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional
public class ReginServiceImpl implements ReginService {

    @Autowired
    private SysRegionMapper SysRegionMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public List<SysRegin> queryList(String name) {
        return SysRegionMapper.queryList(name);
    }

    @Override
    public void add(SysRegin sysRegin) {
        // 先判断编号是否重复
        List<Integer> integers = SysRegionMapper.queryUid(sysRegin.getUid());
        if (!CollectionUtils.isEmpty(integers)) {
            integers.forEach(in -> {
                if (in > 0) {
                    throw new BaseException("编号已重复");
                }
            });
        }
        // 判断名才是否重复
        Integer integer = SysRegionMapper.queryName(sysRegin.getName(), sysRegin.getPuid(), sysRegin.getType());
        if (integer > 0) {
            throw new BaseException("名称已重复");
        }
        SysRegionMapper.insert(sysRegin);
        redisService.deleteObject(CachePrefix.PLATFORM_AREA);
    }

    @Override
    public void update(SysRegin sysRegin) {
        if (ObjectUtil.isEmpty(sysRegin.getUid())) {
            throw new BaseException("uid不能为空");
        }
        //省份下面如果没有被使用的,那么可以修改,区也是同样的
        if (ReginType.province.getKey().equals(sysRegin.getType())) {
            Integer cityCount = SysRegionMapper.getCityCount(sysRegin.getUid());
            if (cityCount > 0) {
                throw new BaseException("该省已被使用,无法删除！");
            }
        } else if (ReginType.city.getKey().equals(sysRegin.getType())) {
            Integer areaCount = SysRegionMapper.getAreaCount(sysRegin.getUid());
            if (areaCount > 0) {
                throw new BaseException("该市已被使用,无法删除！");
            }
        }
        //sysRegin.setDataStatus(DataStatus.delete.getKey());
        //regionMapper.update(sysRegin);
        SysRegionMapper.del(sysRegin.getUid(),sysRegin.getType());
        redisService.deleteObject(CachePrefix.PLATFORM_AREA);
    }

    @Override
    public List<SysRegin> queryProvince() {
        return SysRegionMapper.queryProvince();
    }

    @Override
    public List<SysRegin> querycode(String type, String code) {
        if (type.equals("province")){
        return SysRegionMapper.queryCode(code);}
        return SysRegionMapper.queryCode1(code);
    }

    @Override
    public void edit(SysRegin sysRegin) {
        if (ObjectUtil.isEmpty(sysRegin.getOldUid())) {
            throw new BaseException("旧的编号不能为空!");
        }
        //如果想到不用去差是否重复
        if (!sysRegin.getOldUid().equals(sysRegin.getUid())) {
            //省份下面如果没有被使用的,那么可以修改,区也是同样的
//            if (ReginType.province.getKey().equals(sysRegin.getType())) {
//                Integer cityCount = SysRegionMapper.getCityCount(sysRegin.getOldUid());
//                if (cityCount > 0) {
//                    throw new BaseException("该省已被使用,无法修改！");
//                }
//            } else if (ReginType.city.getKey().equals(sysRegin.getType())) {
//                Integer areaCount = SysRegionMapper.getAreaCount(sysRegin.getOldUid());
//                if (areaCount > 0) {
//                    throw new BaseException("该市已被使用,无法修改！");
//                }
//            }
            // 先判断编号是否重复
            List<Integer> integers = SysRegionMapper.queryUid(sysRegin.getUid());
            if (!CollectionUtils.isEmpty(integers)) {
                integers.forEach(in -> {
                    if (in > 0) {
                        throw new BaseException("编号已重复");
                    }
                });
            }
        }

        // 判断名才是否重复
        Integer integer = SysRegionMapper.queryName(sysRegin.getName(), sysRegin.getPuid(), sysRegin.getType());
        if (integer > 0) {
            throw new BaseException("名称已重复");
        }
        SysRegionMapper.update(sysRegin);
        redisService.deleteObject(CachePrefix.PLATFORM_AREA);
    }


    @Override
    public List<SysProvince> getRegion() {
        List<SysProvince> cacheList = redisService.getCacheList(CachePrefix.PLATFORM_AREA);
        List<SysProvince> sysProvinceList = cacheList;
        if (sysProvinceList == null || sysProvinceList.size() == 0) {
            sysProvinceList = SysRegionMapper.getSysProvinceList();
            redisService.setCacheList(CachePrefix.PLATFORM_AREA, sysProvinceList);
        }
        return sysProvinceList;
    }

    @Override
    public Long[] getReginCode(String[] labels) {
        if (labels == null) {
            return null;
        }
        String provinceName = labels[0];
        String cityName = labels[1];
        String areaName = null;
        SysProvince reginCode = null;
        if (labels.length == 3 && StringUtils.isNotEmpty(cityName)) {
            areaName = labels[2];
            reginCode = SysRegionMapper.getReginCode(provinceName, cityName, areaName);
        } else if (StringUtils.isNotEmpty(cityName)) {
            reginCode = SysRegionMapper.getReginPCCode(provinceName, cityName);
        }
        if (reginCode != null) {
            Long provinceCode = reginCode.getValue();
            Long cityCode = reginCode.getChildren().get(0).getValue();
            Long areaCode = null;
            if (reginCode.getChildren().get(0).getChildren() != null) {
                if (reginCode.getChildren().size() > 0) {
                    SysCity sysCity = reginCode.getChildren().get(0);
                    if (ObjectUtil.isNotEmpty(sysCity)) {
                        if (sysCity.getChildren().size() > 0) {
                            SysArea area = sysCity.getChildren().get(0);
                            if (ObjectUtil.isNotEmpty(area)) {
                                areaCode = area.getValue();
                            }
                        }
                    }
                }
            } else {
                areaCode = null;
            }
            Long[] regins = new Long[3];
            regins[0] = provinceCode;
            regins[1] = cityCode;
            if (areaCode != null) {
                regins[2] = areaCode;
            }
            return regins;
        } else {
            return new Long[0];
        }

    }

    /**
     * 根据code获得name
     *
     * @param pCode
     * @param cCode
     * @param aCode
     * @return
     */
    @Override
    public String getNames(Long pCode, Long cCode, Long aCode) {
        StringBuffer buffer = new StringBuffer("");
        List<SysProvince> regions = getRegion();
        if (ObjectUtil.isNotEmpty(regions)) {
            AtomicReference<SysProvince> sysProvince = new AtomicReference<>(new SysProvince());
            regions.forEach(region -> {
                if (region.getValue().equals(pCode)) {
                    sysProvince.set(region);
                }
            });
            if (ObjectUtil.isNotEmpty(sysProvince.get())) {
                SysProvince sysP = sysProvince.get();
                buffer.append(sysP.getLabel());
                if (ObjectUtil.isNotEmpty(sysP.getChildren())) {
                    SysCity sysC = new SysCity();
                    for (SysCity sysCity : sysP.getChildren()) {
                        if (sysCity.getValue().equals(cCode)) {
                            sysC = sysCity;
                        }
                    }
                    if (ObjectUtil.isNotEmpty(sysC)) {
                        buffer.append(sysC.getLabel());
                        for (SysArea area : sysC.getChildren()) {
                            if (area.getValue().equals(aCode)) {
                                buffer.append(area.getLabel());
                            }
                        }
                    }
                }
            }
        }
        return buffer.toString();
    }


}
